import javax.swing.*;
import java.awt.*;

public class BallGame4 extends JFrame {
    public static void main(String[] args) {
        System.out.println("桌球游戏");
        BallGame4 game4 = new BallGame4();
        game4.launchFrame();
    }
    Image ball = Toolkit.getDefaultToolkit().getImage("images/ball.png");
    Image desk = Toolkit.getDefaultToolkit().getImage("images/desk.png");
    //小球初始位置
    double x=100;
    double y=100;
    double degree = 3.14/3;

    //画窗口的方法
    public void paint (Graphics g){
        System.out.println("窗口被画一次");
        g.drawImage(desk,0,0,null);
        g.drawImage(ball,(int)x,(int)y,null);

        //角度degree改变小球的坐标
        x = x+10*Math.cos(degree);
        y = y +10*Math.sin(degree);

        //边界检测
        if(y>500-40-30||y<40+40){
            degree = -degree;
        }
        if(x<40||x>856-40-30){
            degree = 3.14-degree;
        }
    }
    //窗口加载
    void launchFrame(){
        setSize(856,500);
        setLocation(50,50);
        setVisible(true);//显示窗口，窗口默认是关闭
        //重画窗口，每秒画25次
        while (true){
            repaint(); //调用repaint方法，窗口即可重画
            try {
                Thread.sleep(40);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

}
